<template>
	<view class="content">
		<button type="primary" @tap="send">发送</button>
		<button type="primary" @tap="status">获取状态</button>
	</view>
</template>

<script>
	const port = uni.requireNativePlugin('hpb-serialport');
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
			port.open({
				path: "/dev/ttyS0",
				baudRate: 9600, //可空，默认9600
				parity: 0, //可空，默认0
				dataBits: 8 ,//可空，默认8
				stopBit: 1 //可空，默认1
			}, res=>{
				console.log(res);
				console.log("isOpen->"+res.isOpen);
				if(res.isOpen){
					console.log(res.msg)
				}else{
					console.log(res.msg)
				}
			})
		},
		methods: {
			status(){
				port.getStatus(res=>{
					console.log(res);
					console.log("isOpen->"+res.isOpen);
					if(res.isOpen){
						console.log(res.msg)
					}else{
						console.log(res.msg)
					}
				})
			},
			send(){
				port.addListener({
					sends: ["FF0A01A20B010B3B48FE", "FF0A01A20B010B3B48FE"] //不发送，留[]
				}, async result=>{
					let hex = await this.bytesToHexString(result.bytes, result.size);
					console.log(hex);
					uni.showToast({
						icon: 'none',
						title: hex
					});
				})
			},
			close(){
				port.close();
			},
			bytesToHexString(inarray, size) {
				return new Promise(res => {
					let i, j, x;
					let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
						"B", "C", "D", "E", "F"
					];
					let out = "";
					for (j = 0; j < size; ++j) {
						x = parseInt(inarray[j]) & 0xff;
						i = (x >> 4) & 0x0f;
						out += hex[i];
						i = x & 0x0f;
						out += hex[i];
					}
					res(out)
				})
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
